package com.shibo.order.service.impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.shibo.order.entity.Order;
import com.shibo.order.feign.ProductFeignClient;
import com.shibo.order.service.OrderService;
import com.shibo.product.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallBack")
    @Override
    public Order createOrder(Long productId, Long userId) {

        //获取商品数据
//        Product product = getProductFromRemoteWithLoadBalanced(productId); //版本1
        Product product = productFeignClient.getProduct(productId); //版本2 使用Feign进行远程调用

        Order order = new Order();
        order.setId(1L);

        // 总金额
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickname("张三");
        order.setAddress("六禾");
        //商品列表
        order.setProductList(Arrays.asList(product));
        //流控规则 SphU
//        try {
//            SphU.entry("haha");
//
//            // 总金额
//            order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
//            order.setUserId(userId);
//            order.setNickname("张三");
//            order.setAddress("六禾");
//            //商品列表
//            order.setProductList(Arrays.asList(product));
//        } catch (BlockException e) {
//            // 编码处理
//
//            throw new RuntimeException(e);
//        }

        return order;
    }

    // 兜底回调
    public Order createOrderFallBack(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickname("未知用户");
        order.setAddress("异常信息：" + e.getClass());

        return order;
    }

    /**
     * 远程调用（版本1）
     * @param productId
     * @return
     */
    public Product getProductFromRemote(Long productId) {

        //1.获取到商品服务所在的所有机器的IP+Port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");

        ServiceInstance serviceInstance = instances.get(0);

        //远程URL地址
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/product/"+ productId;

        log.info("远程请求：{}",url);
        //2.给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);

        return product;

    }

    /**
     * 远程调用（进阶（版本2）：负载均衡：loadbalancer）
     * @param productId
     * @return
     */
    public Product getProductFromRemoteWithLoadBalancer(Long productId) {

        //1.负载均衡获取远程服务器
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //远程URL地址
        String url = "http://"+choose.getHost()+":"+choose.getPort()+"/product/"+ productId;

        log.info("远程请求：{}",url);
        //2.给远程发送请求
        Product product = restTemplate.getForObject(url, Product.class);

        return product;

    }


    /**
     * 远程调用（进阶（版本3）：基于注解的负载均衡：@LoadBalanced）
     * @param productId
     * @return
     */
    public Product getProductFromRemoteWithLoadBalanced(Long productId) {

//        //1.负载均衡获取远程服务器
//        ServiceInstance choose = loadBalancerClient.choose("service-product");
//        //远程URL地址
//        String url = "http://"+choose.getHost()+":"+choose.getPort()+"/product/"+ productId;
//
//        log.info("远程请求：{}",url);

        String url = "http://service-product/product/"+ productId;

        log.info("远程请求：{}",url);

        //2.给远程发送请求 service-product会被动态替换
        Product product = restTemplate.getForObject(url, Product.class);

        return product;

    }

}
